package com.aps.apspda.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.SuccessAndFailCallback;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.CTsensorEntity;
import com.aps.apspda.entity.MaterialInfoBean;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.Map;


/**
 * @author huangxin
 * @date 2015/11/10
 * @desc 通用dialog
 */
public class CTsensorFragmentDialog extends AppCompatDialogFragment {
    private SuccessAndFailCallback successAndFailCallback;
    private TextView tvBefore, tvAfter;
    private Button btnRequest, btnConfirm;
    private boolean isFail = true;
    private MaterialInfoBean bean;


    @Override
    public void show(FragmentManager manager, String tag) {
        if (!isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (isFail) {
            successAndFailCallback.onFail();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout((int) (StaticMembers.SCREEN_WIDTH * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    public void setCallBackAndWhere(SuccessAndFailCallback callBack, MaterialInfoBean bean) {
        this.successAndFailCallback = callBack;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_ctsensor, null);
        getDialog().getWindow().setGravity(Gravity.BOTTOM); // 非常重要：设置对话框弹出的位置
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().setWindowAnimations(R.style.BottomDialog); // 添加动画
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        btnConfirm = view.findViewById(R.id.btnConfirm);//确认按钮
        Button btnCancel = view.findViewById(R.id.btnCancel);//取消按钮
        tvBefore = view.findViewById(R.id.tvBefore);
        tvAfter = view.findViewById(R.id.tvAfter);
        btnRequest = view.findViewById(R.id.tvRight);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            getActivity(), false, Toast.LENGTH_SHORT);
                    return;
                }
                isFail = false;
                dismiss();
            }
        });
        btnRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            getActivity(), false, Toast.LENGTH_SHORT);
                    return;
                }
                requestCTsensor("after");
            }
        });
        requestCTsensor("before");
        super.onViewCreated(view, savedInstanceState);
    }

    private void requestCTsensor(final String params) {
        EntityCallBack<BaseEntity<CTsensorEntity>> callBack = new DialogEntityCallBack<BaseEntity<CTsensorEntity>>
                (new TypeToken<BaseEntity<CTsensorEntity>>() {
                }.getType(), getActivity().getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<CTsensorEntity>> response) {
                if (response.body().isSuccess(getActivity())) {
                    CTsensorEntity cTsensorEntity = response.body().getData();
                    tvBefore.setText(cTsensorEntity.getBefor());
                    tvAfter.setText(cTsensorEntity.getAfter());
                    btnRequest.setEnabled(cTsensorEntity.getRequireBtn().equalsIgnoreCase("Y"));
                    btnConfirm.setEnabled(cTsensorEntity.getConfirmBtn().equalsIgnoreCase("Y"));
                    if (params.equals("after")) {
                        ToastUtils.showFreeToast(cTsensorEntity.getMSG(),
                                getActivity(), true, Toast.LENGTH_SHORT);
                    }
                } else {
                    if (params.equals("before")) {
                        dismiss();
                    }
                    AppUtils.loadFail(response.body().getMessage(),getActivity().getSupportFragmentManager(),getContext());//modify by bunny
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<CTsensorEntity>> response) {
                super.onError(response);
                if (params.equals("before")) {
                    dismiss();
                }
                AppUtils.saveErrorMessages(response.getException(), "RequireCTsensorC2E");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", bean.getEqpID());
        map.put("Type", params);
        map.put("MaterialPartNo", bean.getMaterialPartNo());
        map.put("MaterialType", bean.getType());
        map.put("SawThickness", bean.getSawThickness());
        NetUtils.requestNet(this, "/RequireCTsensorC2E", map, callBack);
    }
}
